/**
 * 认证相关功能
 * 处理用户登录、注册、登出和认证状态管理
 */

// 认证状态管理
const auth = {
    /**
     * 获取当前登录用户信息
     * @returns {Object|null} 用户信息对象或null（未登录）
     */
    getCurrentUser: function() {
        // 优先从sessionStorage获取，其次从localStorage获取
        const sessionUser = sessionStorage.getItem('currentUser');
        const localUser = localStorage.getItem('currentUser');
        
        if (sessionUser) {
            return JSON.parse(sessionUser);
        } else if (localUser) {
            return JSON.parse(localUser);
        }
        
        return null;
    },
    
    /**
     * 检查用户是否已登录
     * @returns {boolean} 是否已登录
     */
    isLoggedIn: function() {
        const user = this.getCurrentUser();
        return user !== null && user.token;
    },
    
    /**
     * 获取认证令牌
     * @returns {string|null} 认证令牌或null（未登录）
     */
    getToken: function() {
        const user = this.getCurrentUser();
        return user ? user.token : null;
    },
    
    /**
     * 用户登出
     * 清除存储的用户信息和令牌
     */
    logout: function() {
        sessionStorage.removeItem('currentUser');
        localStorage.removeItem('currentUser');
        
        // 重定向到首页
        // 判断当前是否在pages目录下
        if (window.location.pathname.includes('/pages/')) {
            window.location.href = '../index.html';
        } else {
            window.location.href = 'index.html';
        }
    },
    
    /**
     * 更新导航栏显示
     * 根据登录状态显示不同的导航项
     */
    updateNavigation: function() {
        const isLoggedIn = this.isLoggedIn();
        const user = this.getCurrentUser();
        
        // 获取导航栏中的用户相关元素
        const navUserSection = document.querySelector('.nav-user-section');
        
        if (!navUserSection) return; // 如果元素不存在，直接返回
        
        // 清空现有内容
        navUserSection.innerHTML = '';
        
        if (isLoggedIn) {
            // 已登录状态
            const userDropdown = document.createElement('div');
            userDropdown.className = 'relative';
            
            userDropdown.innerHTML = `
                <button id="userDropdownBtn" class="flex items-center space-x-1 focus:outline-none">
                    <span class="text-white">${user.fullName || user.username}</span>
                    <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                    </svg>
                </button>
                <div id="userDropdownMenu" class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-10 hidden">
                    <a href="health-profile.html" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">健康档案</a>
                    <a href="diet-records.html" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">饮食记录</a>
                    <hr class="my-1">
                    <a href="#" id="logoutBtn" class="block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100">退出登录</a>
                </div>
            `;
            
            navUserSection.appendChild(userDropdown);
            
            // 添加下拉菜单交互
            setTimeout(() => {
                const userDropdownBtn = document.getElementById('userDropdownBtn');
                const userDropdownMenu = document.getElementById('userDropdownMenu');
                const logoutBtn = document.getElementById('logoutBtn');
                
                if (userDropdownBtn && userDropdownMenu) {
                    userDropdownBtn.addEventListener('click', function() {
                        userDropdownMenu.classList.toggle('hidden');
                    });
                    
                    // 点击页面其他地方关闭下拉菜单
                    document.addEventListener('click', function(event) {
                        if (!userDropdownBtn.contains(event.target) && !userDropdownMenu.contains(event.target)) {
                            userDropdownMenu.classList.add('hidden');
                        }
                    });
                }
                
                // 退出登录按钮
                if (logoutBtn) {
                    logoutBtn.addEventListener('click', function(e) {
                        e.preventDefault();
                        auth.logout();
                    });
                }
            }, 0);
            
        } else {
            // 未登录状态
            navUserSection.innerHTML = `
                <a href="pages/login.html" class="hover:text-green-200">登录</a>
                <a href="pages/register.html" class="bg-white text-green-600 px-4 py-2 rounded-lg hover:bg-green-100">注册</a>
            `;
            
            // 如果当前在pages目录下，需要调整路径
            if (window.location.pathname.includes('/pages/')) {
                navUserSection.innerHTML = `
                    <a href="login.html" class="hover:text-green-200">登录</a>
                    <a href="register.html" class="bg-white text-green-600 px-4 py-2 rounded-lg hover:bg-green-100">注册</a>
                `;
            }
        }
    },
    
    /**
     * 初始化认证功能
     * 设置全局认证拦截器和更新导航栏
     */
    init: function() {
        // 更新导航栏
        this.updateNavigation();
        
        // 设置API请求拦截器，添加认证令牌
        const originalFetch = window.fetch;
        window.fetch = function(url, options = {}) {
            // 如果是API请求且用户已登录，添加认证头
            if (url.includes('/api/') && auth.isLoggedIn()) {
                if (!options.headers) {
                    options.headers = {};
                }
                
                options.headers['Authorization'] = `Bearer ${auth.getToken()}`;
            }
            
            return originalFetch(url, options);
        };
    }
};

// 页面加载完成后初始化认证功能
document.addEventListener('DOMContentLoaded', function() {
    auth.init();
});

// 导出auth对象
window.auth = auth;